/*
 * dtim.c
 *
 *  Created on: Feb 8, 2013
 *      Author: bfakhri
 */
#include "dtim.h"
#include "support_common.h"
/*
 * Configures the appropriate DTIM0 registers to delay 
 * for p_usecs microseconds.
 */
void dtim0_delay(int p_usecs)
{
	//Stop timer/reset timer
	//MCF_DTIM0_DTMR &= ~MCF_DTIM_DTMR_RST;
	//Clear counter
	MCF_DTIM0_DTCN =  0xFFFF; //Any write clears
	//Clear Event Reg
	MCF_DTIM0_DTER = 2; //Writing to this clears
	//Set reference
	MCF_DTIM0_DTRR = MCF_DTIM_DTRR_REF(p_usecs-1); //Integer division here to make p_secs into clocks
	//Start timer
	MCF_DTIM0_DTMR |= MCF_DTIM_DTMR_RST;
	//Wait until time has passed
	while(!(MCF_DTIM0_DTER & 0x2)){} 
}

/*
 * Initializes the DTIM0 timer.
 */
void dtim0_init()
{
	//To reset and stop the timer
	MCF_DTIM0_DTMR &= ~MCF_DTIM_DTMR_RST;
	// Clean and assign the prescaler to 80 
	MCF_DTIM0_DTMR &= ~MCF_DTIM_DTMR_PS(255);
	MCF_DTIM0_DTMR |= MCF_DTIM_DTMR_PS(80); 
	//CE = 0: reference mode
	MCF_DTIM0_DTMR &= ~(3 << 6);
	//ORRI = 0: disable DMA request
	MCF_DTIM0_DTMR &= ~(1 << 4);
	//FRR = 1: reset when count reaches ref
	MCF_DTIM0_DTMR |= (1 << 3);
	//CLK = 01: divide clock by 1 (no prescalar)
	MCF_DTIM0_DTMR &= ~(3 << 1);
	MCF_DTIM0_DTMR |= (1 << 1);
	
	//HALTED = 1: timer stops when core is halted
	MCF_DTIM0_DTXMR |= MCF_DTIM_DTXMR_HALTED; 
	//MODE16 = 0: disable mode16
	MCF_DTIM0_DTXMR &= ~MCF_DTIM_DTXMR_MODE16;
}